<script lang="ts" setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import treeSelect from '@/components/tree-select-edl/index.vue'
import wjzs from '@/components/wjzs.vue'
import hwQzb from '@/components/hw-qzb/hw-qzb.vue'
import mtQzb from '@/components/mt-qzb/index.vue'
import dlglService from '@/api/dlgl'
import { getFldm } from '@/utils/get-fldm'
import gdglService from '@/api/gdgl'
import dayjs from 'dayjs'
import { useMainStore } from '@/store/main'
import printFn from '@/utils/print'

const store = useMainStore()

// 移交人类型
interface YjrItem {
  id: string
  mc: string
}

// 入参
const emit = defineEmits(['refresh'])

onMounted(() => {
  // 获取签名方式
  getQmfs()
  // 获取移交人
  getYjr()
})
/*
 * 打开弹框
 */
//
const loading = ref<boolean>(false)
const title = ref<string>('')
// 当前类型
const typeValue = ref<string>('')
// 输入数据
const inputValue = ref<string>('')
// 签名方式
const qmfsValue = ref<string>('')
const qmfsmc = ref<string>('')
// 文件预览地址
const pdfUrl = ref<string>('')
const dialogVisible = ref<boolean>(false)
const openDialog = (type: string, arr: any[]) => {
  step.value = 1
  typeValue.value = type // 'js' | 'gh'
  title.value = type === 'js' ? '接收' : '退回'
  yjrObj.value = {
    id: '',
    mc: '',
  }
  pdfUrl.value = ''
  dialogVisible.value = true
  if (arr.length > 0) {
    const bmsahList = arr.map((el) => el.bmsah)
    typeValue.value === 'js' ? queryJsstclAjxx(bmsahList) : queryGhstclAjxx(bmsahList)
  }
}

/**
 * 当前步骤
 */
const step = ref<number>(1)

// 获取ref
const file = ref()

const wjxhValue = ref()
/**
 * 表格
 */
const formData = ref<any>({
  tableData: [],
})

/**
 * 添加表格项
 */
const addRow = () => {
  if (!inputValue.value) {
    ElMessage.warning('请输入部门受案号')
    return
  }
  typeValue.value === 'js'
    ? queryJsstclAjxx([inputValue.value])
    : queryGhstclAjxx([inputValue.value])
}

/**
 * 接收查询列表
 */
const queryJsstclAjxx = (bmsahList: string[]) => {
  // 查询数据
  const params = {
    bmsahList,
  }
  gdglService
    .queryJsstclAjxx(params)
    .then((res) => {
      if (res.data?.length) {
        const value = {
          ...res.data[0],
        }
        // 校验是否已经添加
        const obj = formData.value.tableData.find((item: any) => item.ajbh === value.ajbh)
        if (obj) {
          ElMessage.warning('已存在该条数据')
        } else {
          inputValue.value = ''
          formData.value.tableData = [...formData.value.tableData, ...res.data]
        }
      } else {
        ElMessage.warning('未查询到相关案件信息')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 退回查询列表
 */
// 退回时案件中是否存在线下接收的
const xxjs = ref(false)
const queryGhstclAjxx = (bmsahList: string[]) => {
  // 查询数据
  const params = {
    bmsahList,
  }
  gdglService
    .queryGhstclAjxx(params)
    .then((res) => {
      if (res.data?.length) {
        const value = {
          ...res.data[0],
        }
        // 校验是否已经添加
        const obj = formData.value.tableData.find((item: any) => item.ajbh === value.ajbh)
        if (obj) {
          ElMessage.warning('已存在该条数据')
        } else {
          inputValue.value = ''
          formData.value.tableData = [...formData.value.tableData, ...res.data]
          if (formData.value.tableData.some((el: any) => el.yjrqmfsdm === 'gd0230002')) {
            xxjs.value = true
          }
        }
      } else {
        ElMessage.warning('未查询到相关案件信息')
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}
/**
 * 删除表格项
 */
const deleteRow = (index: number) => {
  formData.value.tableData.splice(index, 1)
}

/**
 * 下一步
 */
const tableFormRef = ref()
const next = async () => {
  if (formData.value.tableData.length === 0) {
    ElMessage.warning('请添加案件')
    return
  }
  if (!yjrObj.value.id) {
    ElMessage.warning(`请选择业务部门${typeValue.value === 'js' ? '移交人' : '签收人'}`)
    return
  }
  tableFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      step.value = 2
      if (typeValue.value === 'js') {
        pdfUrl.value = await createJsstgdjjd()
        nextTick(() => {
          wjzsRef.value?.init()
        })
      } else {
        createStclgdjjd()
      }
    }
  })
}

/**
 * 上一步
 */
const prev = () => {
  step.value = 1
  wjxhValue.value = ''
  file.value.value = ''
}

/**
 * 获取签名方式
 */
const qmfsList = ref()
const getQmfs = async () => {
  qmfsList.value = await getFldm('gd023')
  if (qmfsList.value.length) {
    qmfsValue.value = qmfsList.value[0].dm
    qmfsmc.value = qmfsList.value[0].mc
  }
}

/**
 * 签名方式change
 */
const qmfsChange = (val: string) => {
  if (xxjs.value && val === 'gd0230001') {
    ElMessage.warning('退回案件中存在线下签名方式接收实体材料的案件，不能选择线上签名方式进行退回')
    return
  }
  pdfUrl.value = ''
  yjrObj.value.id = ''
  yjrObj.value.mc = ''
  const obj = qmfsList.value.find((item: any) => item.dm === val)
  qmfsmc.value = obj ? obj.mc : ''
}

/**
 * 获取移交人
 */
const yjrObj = ref<YjrItem>({
  id: '',
  mc: '',
})
const yjrList = ref<any[]>([])
const getYjr = () => {
  // 查询数据
  const params = {
    code: '',
    dwbm: store.$state.userInfo?.dwbm,
    rymc: '',
  }
  dlglService
    .queryRyybmTree(params)
    .then((res) => {
      if (res.data?.list) {
        yjrList.value = res.data.list
        resetTree(yjrList.value)
      } else {
        yjrList.value = []
      }
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 重构树
 */
const resetTree = (arr: any[]) => {
  arr.forEach((el) => {
    el.dm = el.bmbm || el.rybm
    el.mc = el.bmmc || el.rymc
    if (el.list?.length) {
      el.children = el.list
      resetTree(el.children)
    }
  })
}

/**
 * 树点击
 */
const nodeChange = (val: string, node: any, mc: string) => {
  const value = yjrObj.value as any
  value[mc] = node.mc
}

/**
 * 生成接收实体归档交接单(接收实体材料按钮使用)
 */
const jsjjdParams = ref<any>()
const createJsstgdjjd = async (flag?: boolean) => {
  const params = {
    dwmc: store.$state.userInfo?.dwmc,
    list: formData.value.tableData.map((el: any, index: number) => {
      return {
        ajbh: el.ajbh,
        ajmc: el.ajmc,
        bmsah: el.bmsah,
        cbbm: el.cbbmmc,
        ghr: '',
        ghrq: '',
        gpsl: el.gpsl,
        index: index,
        jsr: '',
        jsrq: '',
        qsr: typeValue.value !== 'js' ? yjrObj.value.id : '',
        qsrq: typeValue.value !== 'js' ? dayjs().format('YYYY-MM-DD') : '',
        yjr: typeValue.value === 'js' ? yjrObj.value.id : '',
        yjrq: typeValue.value === 'js' ? dayjs().format('YYYY-MM-DD') : '',
        zzjsl: el.zzajsl,
        zzzpsl: el.zzzpsl,
      }
    }),
    yjrdzqmwjxh: flag ? wjxhValue.value : '',
  }
  jsjjdParams.value = params
  let url = ''
  await gdglService
    .createJsstgdjjd(params)
    .then((res) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        url = window.URL.createObjectURL(res.data)
      }
      step.value = 2
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
      return ''
    })
    .finally(() => {
      loading.value = false
    })

  return url
}

/**
 * 接收实体案卷
 */
const receiveStaj = () => {
  if (formData.value.tableData.length === 0) {
    ElMessage.warning('请添加案件')
    return
  }
  const params = paramsValue.value
  gdglService
    .receiveStaj(params)
    .then(async () => {
      ElMessage.success('接收成功')
      if (qmfsValue.value === 'gd0230001') {
        pdfUrl.value = await createJsstgdjjd(true)
        nextTick(() => {
          wjzsRef.value?.init()
        })
      } else {
        closeDialog()
      }
      emit('refresh')
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

/**
 * 退回实体卷宗
 */
const updateGhstcl = () => {
  const params = paramsValue.value
  gdglService
    .updateGhstcl(params)
    .then(() => {
      ElMessage.success('退回成功')
      if (qmfsValue.value === 'gd0230001') {
        createStclgdjjd()
      } else {
        closeDialog()
      }
      emit('refresh')
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
    .finally(() => {
      loading.value = false
    })
}

const printJsjjd = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '接收实体归档交接单.pdf',
    loadingHeader: {},
    loadingParam: jsjjdParams.value,
    loadingUrl: `${window.IPCONFIG}/api/gdgl/createJsstgdjjd`,
    requestMethodName: 'POST',
  }
  printFn(params)
}

const printGhjjd = () => {
  const params = {
    fileSource: '2',
    localFilePathList: [],
    fileName: '归还实体归档交接单.pdf',
    loadingHeader: {},
    loadingParam: ghjjdParams.value,
    loadingUrl: `${window.IPCONFIG}/api/gdgl/createStclgdjjd`,
    requestMethodName: 'POST',
  }
  printFn(params)
}
const print = () => {
  typeValue.value === 'js' ? printJsjjd() : printGhjjd()
}
/*
 * 打开签名板
 */
const mtQzbRef = ref()
const handleQm = () => {
  mtQzbRef.value.openDialog()
  // hwQzbRef.value.socketBegin()
}
/*
 * 保存数据
 */
const hwQzbRef = ref()
const paramsValue = ref<any>()
const saveData = async () => {
  if (xxjs.value && qmfsValue.value === 'gd0230001') {
    ElMessage.warning('退回案件中存在线下签名方式接收实体材料的案件，不能选择线上签名方式进行退回')
    return
  }
  if (!yjrObj.value.id) {
    ElMessage.warning(`请选择业务部门${typeValue.value === 'js' ? '移交人' : '签收人'}`)
    return
  }
  if (!mtQzbRef.value.qmtp) {
    ElMessage.warning(`请${typeValue.value === 'js' ? '移交人' : '签收人'}签名`)
    return
  }

  tableFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      let wjxh = ''
      if (qmfsValue.value === 'gd0230001') {
        const file = base64ToFile(mtQzbRef.value.qmtp, '电子签名')
        // 上传文件
        wjxh = await singleUploadFile(file)
        // 预览文件
        wjxhValue.value = wjxh
        // 提交
        submit()
      }
    }
  })
}
const wjzsRef = ref()
/**
 * 生成接收实体归档交接单(接收实体材料按钮使用)
 */
const ghjjdParams = ref<any>()
const createStclgdjjd = () => {
  loading.value = true
  const params = {
    ajbhList: formData.value.tableData.map((el: any) => el.ajbh),
    qsrdzqmwjxh: qmfsValue.value === 'gd0230001' ? wjxhValue.value : '',
  }
  ghjjdParams.value = params
  gdglService
    .createStclgdjjd(params)
    .then((res) => {
      if (res.data.type === 'application/json') {
        const reader = new FileReader()
        reader.onload = () => {
          const jsonData =
            typeof reader.result === 'string' ? JSON.parse(reader.result) : reader.result
          ElMessage({ type: 'warning', message: jsonData.message })
        }
        reader.readAsText(res.data)
      } else {
        pdfUrl.value = window.URL.createObjectURL(res.data)
        step.value = 2
        nextTick(() => {
          wjzsRef.value?.init()
        })
      }
      loading.value = false
    })
    .catch((err) => {
      !err.isError && ElMessage({ type: 'warning', message: err.message })
    })
}

/**
 * 提交
 */
const submit = () => {
  if (!wjxhValue.value) {
    ElMessage.warning('未找到文件序号')
    return
  }
  const gdjlxxList = formData.value.tableData.map((el: any) => {
    return {
      gdbh: el.gdbh,
      gdjlbh: el.gdjlbh,
      gpsl: el.gpsl,
      zzajsl: el.zzajsl,
      zzzpsl: el.zzzpsl,
    }
  })

  // 参数组装
  if (typeValue.value === 'js') {
    paramsValue.value = {
      gdjlxxList: gdjlxxList,
      wjxh: wjxhValue.value || pdfUrl.value,
      yjrq: dayjs().format('YYYY-MM-DD'),
      yjrqmfsdm: qmfsValue.value,
      yjrqmfsmc: qmfsmc.value,
      yjrbh: yjrObj.value.id,
      yjrxm: yjrObj.value.mc,
    }
  } else {
    paramsValue.value = {
      gdjlxxList: gdjlxxList,
      wjxh: wjxhValue.value || pdfUrl.value,
      qsrq: dayjs().format('YYYY-MM-DD'),
      qsrqmfsdm: qmfsValue.value,
      qsrqmfsmc: qmfsmc.value,
      qsrbh: yjrObj.value.id,
      qsrxm: yjrObj.value.mc,
    }
  }
  typeValue.value === 'js' ? receiveStaj() : updateGhstcl()
}

/**
 * base64转换file
 */
const base64ToFile = (base64: any, fileName: string) => {
  const arr = base64.split(',')
  const mime = arr[0].match(/:(.*?);/)[1]
  const bstr = atob(arr[1])
  let n = bstr.length
  const u8arr = new Uint8Array(n)

  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, { type: mime })
}

/**
 * 上传文件
 */
const singleUploadFile = async (file: any) => {
  const formData = new FormData()
  formData.append('file', file)
  const res = await gdglService.singleUploadFile(formData).catch((err) => {
    !err.isError && ElMessage({ type: 'warning', message: err.message })
    return {
      data: {
        wjxh: '',
      },
    }
  })
  return res.data?.wjxh || ''
}

// 点击上传按钮
const submitImg = () => {
  file.value.multiple = false
  file.value.accept = '.pdf'
  file.value.click()
}

const uploadFile = async (e: any) => {
  const file = e.target.files[0]
  wjxhValue.value = await singleUploadFile(file)
  if (wjxhValue.value) {
    const fileType = file.type
    const blob = new Blob([file], { type: fileType || 'application/*' })
    const blobUrl = window.URL.createObjectURL(blob)
    pdfUrl.value = blobUrl
    nextTick(() => {
      wjzsRef.value?.init()
    })
  }
}

const closeDialog = () => {
  formData.value.tableData = []
  wjxhValue.value = ''
  pdfUrl.value = ''
  file.value.value = ''
  dialogVisible.value = false
  inputValue.value = ''
  qmfsValue.value = 'gd0230001'
}

const rules = {
  gpsl: [{ required: true, message: '必填', trigger: 'blur' }],
  zzzpsl: [{ required: true, message: '必填', trigger: 'blur' }],
}

// 下载按钮
const download = () => {
  const downloadElement = document.createElement('a')
  downloadElement.href = pdfUrl.value
  downloadElement.download = `${title.value}材料交接单.pdf`
  document.body.appendChild(downloadElement)
  downloadElement.click() //点击下载
  document.body.removeChild(downloadElement) //下载完成移除元素
}

defineExpose({ openDialog })
</script>
<template>
  <el-dialog
    v-model="dialogVisible"
    v-if="dialogVisible"
    :title="`${title}实体材料`"
    width="80%"
    :close-on-click-modal="false"
  >
    <div class="dialog-box">
      <div class="aj-choose-box" v-if="step === 1">
        <div class="aj-choose-left">
          <el-form ref="tableFormRef" :model="formData">
            <div class="table-wrap">
              <el-table :data="formData.tableData" height="100%">
                <el-table-column type="index" label="序号" width="55" />
                <el-table-column prop="ajmc" label="案件名称" show-overflow-tooltip />
                <el-table-column prop="bmsah" label="部门受案号" show-overflow-tooltip />
                <el-table-column prop="cbbmmc" label="承办部门" width="100" show-overflow-tooltip />
                <el-table-column prop="cbjcg" label="检察官" width="100" show-overflow-tooltip />
                <el-table-column prop="zzajsl" label="纸质卷" width="80" />
                <el-table-column prop="gpsl" width="100">
                  <template #header>
                    <div><span class="required-column">*</span>光盘</div>
                  </template>
                  <template #default="scope">
                    <el-form-item :prop="`tableData.${scope.$index}.gpsl`" :rules="rules.gpsl">
                      <el-input-number
                        class="number-input"
                        v-model="scope.row.gpsl"
                        :min="0"
                        :controls="false"
                      ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="zzzpsl" width="100">
                  <template #header>
                    <div><span class="required-column">*</span>纸质照片</div>
                  </template>
                  <template #default="scope">
                    <el-form-item :prop="`tableData.${scope.$index}.zzzpsl`" :rules="rules.zzzpsl">
                      <el-input-number
                        class="number-input"
                        v-model="scope.row.zzzpsl"
                        :min="0"
                        :controls="false"
                      ></el-input-number>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="60" fixed="right">
                  <template #default="scope">
                    <el-link type="primary" :underline="false" @click="deleteRow(scope.$index)"
                      >删除</el-link
                    >
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </el-form>

          <div class="bmsah-box">
            <span>部门受案号</span>
            <el-input v-model="inputValue" placeholder="请输入" clearable />
            <el-button type="primary" @click="addRow">添加</el-button>
          </div>
        </div>
        <div class="aj-choose-right">
          <div class="qmfs-box">
            <div class="yjr-label">签名方式:</div>
            <el-select v-model="qmfsValue" @change="qmfsChange">
              <el-option v-for="item in qmfsList" :key="item.dm" :label="item.mc" :value="item.dm">
              </el-option>
            </el-select>
          </div>
          <div class="qm-box">
            <div class="yjr-box">
              <div class="yjr-label">
                请选择业务部门{{ typeValue === 'js' ? '移交人' : '签收人' }}:
              </div>
              <tree-select
                v-model="yjrObj.id"
                :options="yjrList"
                node-key="ryid"
                @node-change="(data:string, node:any)=> nodeChange(data, node,'mc')"
              ></tree-select>
            </div>
            <div class="yjrqm-box" v-if="qmfsValue === 'gd0230001'">
              <div class="yjr-label">
                请业务部门{{ typeValue === 'js' ? '移交人' : '签收人' }}签名:
                <el-button style="min-width: auto" @click="handleQm">签名</el-button>
              </div>
              <div class="canvas-box">
                <!-- <hwQzb ref="hwQzbRef"></hwQzb> -->
                <mtQzb ref="mtQzbRef"></mtQzb>
              </div>
            </div>
          </div>
        </div>
      </div>
      <div class="pdf-box" v-else-if="step === 2" v-loading="loading">
        <!-- <wjzs :src="pdfUrl" />-->
        <wjzs ref="wjzsRef" wjlx="pdf" :url="pdfUrl" />
      </div>
      <input style="display: none" type="file" @change="uploadFile" ref="file" />
    </div>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="next" v-if="step === 1 && qmfsValue !== 'gd0230001'"
          >下一步</el-button
        >
        <el-button type="primary" @click="prev" v-if="step === 2 && qmfsValue !== 'gd0230001'"
          >上一步</el-button
        >
        <el-button
          type="primary"
          @click="saveData"
          :loading="loading"
          v-if="step === 1 && qmfsValue === 'gd0230001'"
          >确定</el-button
        >
        <el-button type="primary" v-if="step === 2" @click="download">下载</el-button>
        <el-button type="primary" v-if="step === 2" @click="print">打印</el-button>
        <el-button type="primary" v-if="step === 2 && !wjxhValue" @click="submitImg"
          >上传</el-button
        >
        <el-button
          type="primary"
          @click="submit"
          :loading="loading"
          v-if="step === 2 && wjxhValue && qmfsValue !== 'gd0230001'"
          >确定</el-button
        >
        <el-button @click="closeDialog">取消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<style lang="scss" scoped>
.dialog-box {
  width: 100%;
  height: 70vh;
}
.aj-choose-box {
  width: 100%;
  height: 100%;
  display: flex;
  // flex-direction: column;
  .aj-choose-left {
    width: calc(100% - 450px);
    height: 100%;
    padding: 10px;
    border: 1px solid #dae4f1;
    .el-form {
      height: calc(100% - 45px);
      .table-wrap {
        height: 100%;
        .required-column {
          padding-right: 4px;
          color: var(--el-color-danger);
        }
        :deep(.el-form-item) {
          margin-bottom: 0px;
        }
      }
    }
  }
  .aj-choose-right {
    width: 440px;
    display: flex;
    flex-direction: column;
    margin-left: 10px;
    padding: 10px;
    border: 1px solid #dae4f1;
  }
  .qmfs-box {
    .yjr-label {
      height: 34px;
      line-height: 34px;
      color: #526a89;
    }
    .el-select {
      width: 200px;
    }
  }
  .qm-box {
    display: flex;
    flex-direction: column;
    flex: 1;
    flex-shrink: 0;
    .yjrqm-box {
      height: 300px;
      float: left;
      .yjr-label {
        margin-bottom: 5px;
      }
    }
    .yjr-box {
      width: 80%;
      float: left;
      margin-bottom: 5px;
    }
    .yjr-label {
      height: 34px;
      line-height: 34px;
      color: #526a89;
    }
  }
  .canvas-box {
    width: 100%;
    height: calc(100% - 50px);
    border: 1px solid #dae4f1;
    overflow: hidden;
  }
}
.bmsah-box {
  display: flex;
  align-items: center;
  margin-top: 10px;
  .el-input {
    margin: 0 10px;
    width: 300px;
  }
}
.number-input {
  width: 70px;
}

.pdf-box {
  width: 100%;
  height: 100%;
}
</style>
